import axios, { AxiosInstance, RawAxiosRequestHeaders } from 'axios';
import axiosAdapterUniapp from 'axios-adapter-uniapp';

export function getAxiosClient(
  appURL: string,
  useToken?: boolean,
  token?: () => string,
  tokenType?: 'Bearer' | 'token',
): AxiosInstance {
  const serviceAxios = axios.create({
    baseURL: appURL,
    headers: getRequestHeaders(useToken, tokenType, token),
    withCredentials: true,
    adapter: axiosAdapterUniapp as any
  });

  serviceAxios.interceptors.response.use((res: any) => {
    const cookies = res.header["Set-Cookie"];
    if (cookies && cookies.length > 0) {
			if (cookies[0].indexOf('Guest') < 0) {
        wx.setStorageSync('token', cookies);
			}
		}
    return res;
  });

  return serviceAxios;
}

export function getRequestHeaders(
  useToken: boolean = false,
  tokenType?: 'Bearer' | 'token',
  token?: () => string,
): RawAxiosRequestHeaders {
  const headers: RawAxiosRequestHeaders = {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
  };

  if (useToken && tokenType && token) {
    headers.Authorization = `${tokenType} ${token()}`;
  }

  const cookie = wx.getStorageSync('token');
	if (cookie) {
    headers['Cookie'] = cookie;
  }
  console.log('headers:', headers);

  // in case of browser environments
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    if (window.location) {
      headers['X-Frappe-Site-Name'] = window.location.hostname;
    }
    if (window.csrf_token && window.csrf_token !== '{{ csrf_token }}') {
      headers['X-Frappe-CSRF-Token'] = window.csrf_token;
    }
  }

  return headers;
}
